/**
 * 
 */
package com.oron3.bouncer.objects;

import com.oron3.bouncer.genericgl.GLWorld;
import com.oron3.bouncer.genericgl.WorldConstants;
import com.oron3.bouncer.objects.shapes.Intersection;
import com.oron3.bouncer.objects.shapes.Line;
import com.oron3.bouncer.objects.shapes.Point;
import com.oron3.bouncer.objects.shapes.Rectangle;
import com.oron3.bouncer.objects.shapes.Shape;

/**
 * @author Ofek
 *
 */
public class GameArc extends GLArc {

	/**
	 * @param leftBottom
	 * @param lx
	 * @param ly
	 * @param lz
	 */
	public GameArc(final Point leftBottom, final float lx, final float ly, final float lz) {
		super(leftBottom, lx, ly, lz);
		setColor(WorldConstants.red);
	}
	/**
	 * @param ball
	 * @param dt 
	 * @return 
	 */
	public float moveBall(final GLWorld glWorld,final GLBall ball, float dt) {
		setColor(WorldConstants.red);
		Point nextPlace = ball.center.add(ball.v.mul(dt));
		Line ballDirection = new Line(ball.center,nextPlace);

		if (isInside(nextPlace) && dt>0) {
			dt = chopMovement(glWorld,ball,nextPlace,dt,ballDirection);
			nextPlace = ball.center.add(ball.v.mul(dt));
			ballDirection = new Line(ball.center,nextPlace);
		}
		return dt;
	}
	/**
	 * @param glWorld 
	 * @param ball 
	 * @param nextPlace 
	 * @param dt 
	 * @param ballDirection 
	 * @return 
	 * 
	 */
	private float chopMovement(final GLWorld glWorld, final GLBall ball, final Point nextPlace, final float dt, final Line ballDirection) {
		final float distance = nextPlace.sub(ball.center).length();
		for ( final Rectangle o : recs ) {
			final GLRectangle r = ((GLRectangle)o);
			if (ballDirection.d.dot(r.p.n)<0) continue;
			final Intersection intersection = r.intersection(ballDirection);
			if ( intersection!=null && intersection.shapes.size()==1 && (intersection.shapes.get(0) instanceof Point)) {
				final Shape shape = intersection.shapes.get(0);
				final Point p = (Point) shape;
				final float hitDistance = p.sub(ball.center).length();
				final float dt1 = dt * (hitDistance/distance);
				ball.step(dt1,glWorld);
				ball.setPosition(p);
				r.setColor(WorldConstants.blue);
				ball.bounce(r.p.n);
				return dt-dt1;
			}
		}
		return dt;
		//throw new IllegalArgumentException();
	}

}
